﻿using System;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using FreeSql;
using TomNet.Core.Options;
using TomNet.Extensions;
using TomNet.Exceptions;
using System.Collections.Generic;

namespace TomNet.FreeSql
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddFreeSql(this IServiceCollection services, Action<List<Type>> entities = null)
        {
            IConfiguration configuration = services.GetConfiguration();
            var options = configuration.GetTomNetOptions();
            var dbcontext = options.DbContexts["Default"];

            if (dbcontext == null)
            {
                throw new TomNetException("配置文件中缺少DbContexts节点");
            }

            var dbType = DbHelper.DatabaseTypeToDbType(dbcontext.DatabaseType);

            var connstr = dbcontext.ConnectionString;

            if (connstr.IsNullOrEmpty())
            {
                throw new TomNetException("配置文件中缺少数据库连接字符串");
            }

            var freeSqlBuilder = new FreeSqlBuilder()
                    .UseConnectionString(dbType, connstr)
                    .UseAutoSyncStructure(dbcontext.AutoMigrationEnabled)
                    .UseLazyLoading(false)
                    .UseNoneCommandParameter(true);

            var fsql = freeSqlBuilder.Build();
            services.AddFreeRepository();
            services.AddScoped<UnitOfWorkManager>();
            services.AddSingleton(fsql);

            if (dbcontext.AutoMigrationEnabled)
            {
                if (dbType == DataType.Oracle)
                {
                    fsql.CodeFirst.IsSyncStructureToUpper = true;
                }

                if (entities != null)
                {
                    List<Type> tables = new List<Type>();
                    entities(tables);
                    fsql.CodeFirst.SyncStructure(tables.ToArray());
                }
            }
            return services;
        }
    }
}
